//
//  User.swift
//  DiDiRecycle
//
//  Created by abb on 16/7/28.
//  Copyright © 2016年 abb. All rights reserved.
//

import UIKit

class User: NSObject,NSCoding {
    /// 用户id
    var id: Int?
    /// 用户昵称
    var nickName: String?
    /// 电话
    var phoneNumber: String?
    /// 密码
    var password: String?
    /// 用户头像字符串
    var userImageUrlStr: String? {
        didSet {
            userImageUrl = NSURL(string: "http://" + userImageUrlStr!)
        }
    }
    /// 用户头像url
    var userImageUrl: NSURL?
    /// 用户高清头像字符串
    var userImageUrlHdStr: String? {
        didSet {
            userImageUrlHd = NSURL(string: "http://" + userImageUrlHdStr!)
        }
    }
    /// 用户高清头像url
    var userImageUrlHd: NSURL?
        
    /**
     初始化
     */
    init(dict: [String:AnyObject]) {
        super.init()
        id = dict["id"] as? Int
        nickName = dict["nick_name"] as? String
        phoneNumber = dict["phone_number"] as? String
        password = dict["password"] as? String

        if let userImageUrlStr = dict["userimage"]?["user_image_url"] as? String {
            userImageUrl = NSURL(string: "http://" + userImageUrlStr)
            self.userImageUrlStr = userImageUrlStr
        }
        if let userImageUrlHdStr = dict["userimage"]?["user_image_url_hd"] as? String {
            userImageUrlHd = NSURL(string: "http://" + userImageUrlHdStr)
            self.userImageUrlHdStr = userImageUrlHdStr
        }
    }
    
    class func loadUserBySms(phoneNumber:String,zone:String,code:String,finished:(model:User?,resultCode:Int?,error:String?)->()) {
        UserDAO.getUserBySms(phoneNumber, zone: zone, code: code) { (dict,resultCode,error) in
            // 错误判断
            if dict == nil {
                finished(model: nil,resultCode: nil, error: error)
                return
            }
            if error != nil {
                finished(model: nil,resultCode: nil, error: error)
                return
            }
            // 将字典转换为模型
            let model = User(dict: dict!)
            // 回调闭包
            finished(model: model,resultCode: resultCode, error: nil)
            
        }
    }
    class func loadUserByMerchant(userID:Int,finished:(model:User?,error:String?)->()) {
        UserDAO.getUserByMerchant(userID) { (bool, result,error) in
            if bool {
                let model = User(dict: result!)
                finished(model: model, error: nil)
                return
            }
            finished(model: nil, error: error)
        }
    }
    /**
     检测用户是否登录
     */
    class func userLogin() ->Bool {
        let userDefaults = NSUserDefaults.standardUserDefaults()
        if let phoneNum = userDefaults.objectForKey("lastLoginUser") as? String {
            return User.loadUser(phoneNum) != nil
        }
        return false
    }
    
    // MARK: - 保存和读取
    /**
     保存授权模型
     */
    static let filePath = "user.plist".cacheDir()
    func saveAccount() -> Bool{
        let userData = NSKeyedArchiver.archivedDataWithRootObject(self)
        let userDefaults = NSUserDefaults.standardUserDefaults()
        userDefaults.setObject(userData, forKey: phoneNumber!)
        userDefaults.setObject(phoneNumber, forKey: "lastLoginUser")
        return true
    }
    
    static var user:User?
    /**
     加载授权模型
     */
    class func loadUser(key:String = "",onlyRead:String = "0") -> User? {
        
        // 1.判断是否已经加载过
        if self.user != nil {
            return self.user
        }
        
        // 2.加载授权模型
        let userDefaults = NSUserDefaults.standardUserDefaults()
        if let data = userDefaults.objectForKey(key) as? NSData {
            self.user = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? User
            if onlyRead == "0" {
                userDefaults.setObject(self.user!.phoneNumber, forKey: "lastLoginUser")
            }

        }
        return self.user
    }
    /**
     退出登录
     */
    class func exitUser(){
        user = nil
    }
    class func updataUser(user:User) {
        self.user = user
        user.saveAccount()
    }
    // MARK: - NSCoding
    // 将对象写入文件
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(id, forKey: "id")
        aCoder.encodeObject(nickName, forKey: "nickName")
        aCoder.encodeObject(phoneNumber, forKey: "phoneNumber")
        aCoder.encodeObject(password, forKey: "password")
        // TODO: - 如果没设置头像
        aCoder.encodeObject(userImageUrlStr, forKey: "userImageUrl")
        aCoder.encodeObject(userImageUrlHdStr, forKey: "userImageUrlHd")
        aCoder.encodeObject(userImageUrl, forKey: "userImageUrl")
        aCoder.encodeObject(userImageUrlHd, forKey: "userImageUrlHd")
        
    }
    // 从文件中读取对象
    required init?(coder aDecoder: NSCoder) {
        
        id = aDecoder.decodeObjectForKey("id") as? Int
        nickName = aDecoder.decodeObjectForKey("nickName") as? String
        phoneNumber = aDecoder.decodeObjectForKey("phoneNumber") as? String
        password = aDecoder.decodeObjectForKey("password") as? String
        // TODO: - 如果没设置头像
        userImageUrlStr = aDecoder.decodeObjectForKey("userImageUrlStr") as? String
        userImageUrlHdStr = aDecoder.decodeObjectForKey("userImageUrlHdStr") as? String
        userImageUrl = aDecoder.decodeObjectForKey("userImageUrl") as? NSURL
        userImageUrlHd = aDecoder.decodeObjectForKey("userImageUrlHd") as? NSURL
    }

}
